#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>

int main(int argc, char **argv)
{
    struct sockaddr_rc loc_addr = { 0 }, rem_addr = { 0 };
    char buf[1024] = { 0 };
    int s, client;
    socklen_t opt = sizeof(rem_addr);
    
    int rate = 0;
    int channel = 0;
    printf("Inserisci il canale del sensore: ");
    scanf("%d", &channel);
    printf("Inserisci la velocità di risposta del sensore: ");
    scanf("%d", &rate);

    // local bluetooth adapter
    loc_addr.rc_family = AF_BLUETOOTH;
    loc_addr.rc_bdaddr = *BDADDR_ANY;
    loc_addr.rc_channel = (uint8_t) channel;

    while(1){
	    // allocate socket
	    s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);

	    // bind socket to port 1 of the first available 
	    bind(s, (struct sockaddr *)&loc_addr, sizeof(loc_addr));

	    // put socket into listening mode
	    listen(s, 1);

	    // accept one connection
	    client = accept(s, (struct sockaddr *)&rem_addr, &opt);

	    ba2str( &rem_addr.rc_bdaddr, buf );
	    fprintf(stderr, "accepted connection from %s\n", buf);
	    memset(buf, 0, sizeof(buf));

	   int w = 0;
	   int r = 0;

	    while(w!=-1 && r!=-1){
		// read data from the client
		r = read(client, buf, sizeof(buf));
		printf("received [%s]\n", buf);
		sleep(rate);
		int value = random()%100;
		char valueChar[5];
		sprintf(valueChar, "%d",value);
	    	w= write(client,valueChar,5);
		printf("Ho mandato: %s\n",valueChar);
		sleep(1);
	    }

	    // close connection
	    close(client);
	    close(s);
    }
    return 0;
}

